#include "TankEntity.h"




TankEntity::TankEntity(int id, int type, double x, double y, Rect* targetRect)
{
	_data = new TankData(id, type, x, y);
	startx = x;
	life = 20;
	spriteDup = 0;
	_data->targetRect = targetRect;
	_bulletContainer = new BulletContainer(GameDeviceSingleton::getInstance()->getPlayerRect(), BulletArmy);
	_bulletContainer->updateData(_GUN_DATA_DISTANCE_BULLET, _GUN_DATA_DELAY_TWO_BULLET, 5, _ID_BULLET_TANK);
}

void TankEntity::update(long time)
{
	if (_data->isDead) return;
	updateState();
	updatePhysics();
	_data->sprites->updateCurrent();
	if (_bulletContainer->checkCanFire()) {
		_bulletContainer->fire(_data->getRect()->X - 60, _data->getRect()->Y + 30, 0, GameDeviceSingleton::getInstance()->getPlayerRect(), false);
	}
	_bulletContainer->update(time);
}

void TankEntity::updateState()
{
	checkMoveState();
	checkFireState();
}

void TankEntity::checkMoveState()
{
	double deltax = _data->rect->X - _data->targetRect->X;
	if (deltax < 500 && startx - _data->rect->X < 150) {
		_data->rect->Vx = -1;
		_data->sprites->currentSprite->setStartEnd(0 + spriteDup,2 + spriteDup);
	} else {
		_data->rect->Vx = 0;
	}
}

void TankEntity::checkFireState()
{
	double deltax = _data->rect->X - _data->targetRect->X  - 70;
	if (deltax > 300) {
		_data->sprites->currentSprite->setStartEnd(0 + spriteDup,2  + spriteDup);
	} else if (deltax <= 300 && deltax > 100) {
		_data->sprites->currentSprite->setStartEnd(2 + spriteDup,4 + spriteDup);		
	} else {
		_data->sprites->currentSprite->setStartEnd(4 + spriteDup, 6 + spriteDup);
	}
}

void TankEntity::draw(long time)
{
	if (!_data->isDead)
		_data->sprites->draw();
	_bulletContainer->draw(time);
}

void TankEntity::updatePhysics()
{
	_data->rect->X += _data->rect->Vx;
	_data->rect->Y += _data->rect->Vy;
}

void TankEntity::updateData(int action, int actiondata)
{
	if (action == ACTIONS_IS_HURT) {
		life -= actiondata;

		if (life <= 0 && !_data->isDead) {
			_data->isDead = true;
			_data->canInteract = false;
			EffectManager::getInstatnse()->createEffect(EffectType::TYPE_Bridge_Fier, _data->rect->X, _data->rect->Y);
		} else {
			if (life <= 5) {
				spriteDup = 18;
			} else if (life <= 10) {
				spriteDup = 12;
			} else if (life <= 15) {
				spriteDup = 6;
			} 
		}
	}
}

AbstractData* TankEntity::getAbstractData()
{
	return _data;
}
